from web3 import Web3
import time
import psycopg2
import base64
import pickle

w3 = None
conn = None
cursor = None

def log_loop(event_filter, poll_interval):
    global conn, cursor
    while True:
        for entry in event_filter.get_new_entries():
            print(entry)
            '''
            tx_counts = w3.eth.get_block_transaction_count(entry)
            for i in range(tx_counts):
                tx = w3.eth.get_transaction_by_block(entry, i)
                if tx['input'][:6]=='0xffff':
                    data = Web3.toBytes(hexstr=tx['input'][6:])
                    data = pickle.loads(data)
                    sqlstr = "INSERT INTO transaction(from_addr,to_addr,vin_id,file,record_num,location,"+\
                        "date_from,date_to,metadata,contract_addr,price,rawdata,status) values("+\
                        "'"+tx['from']+"',"+\
                        "'"+tx['to']+"',"+\
                        "'"+data['VIN']+"',"+\
                        "'"+data['File']+"',"+\
                        str(data['Record_num'])+","+\
                        "'"+data['Location']+"',"+\
                        "'"+data['Date_from']+"',"+\
                        "'"+data['Date_to']+"',"+\
                        "'"+','.join(data['Description'])+"',"+\
                        "'"+data['Contract_address']+"',"+\
                        str(data['Price'])+","+\
                        "'"+str(base64.b64encode(pickle.dumps(tx)), encoding='utf-8')+"','New')"
                    cursor.execute(sqlstr)
            conn.commit()
            '''
        time.sleep(poll_interval)

def main():
    global account_address
    global w3
    global conn, cursor
    w3 = Web3(Web3.IPCProvider('data/geth.ipc'))
    conn = psycopg2.connect(database="ether", user="postgres",password="postgres", host="127.0.0.1", port="5432")
    cursor = conn.cursor()
    #block_filter = w3.eth.filter('latest', address='0x6CA25fbE7e2dCD116a81425b8FDCC4a5DC6c00D5')
    #block_filter = w3.eth.filter({'fromBlock':'latest', 'address':'0x6CA25fbE7e2dCD116a81425b8FDCC4a5DC6c00D5'})
    block_filter = w3.eth.filter({'fromBlock':'latest'})
    log_loop(block_filter, 2)

if __name__ == '__main__':
    main()